package com.wpre.captchademo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.wpre.captchademo.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-10-31
 * Time: 20:12
 */
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    //注入
    @Autowired
    private CaptchaProperties captchaProperties;



    @Value("${captcha.session.key}")
    private String key;
    @Value("${captcha.session.datetime}")
    private String datetime;


    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());

        String code = lineCaptcha.getCode();


        //设置session,把验证码信息存储到session中
        session.setAttribute(key, code);
        session.setAttribute(datetime, new Date());


        //验证码写入浏览器
        lineCaptcha.write(response.getOutputStream());

        //设置ContentType
        response.setContentType("image/jpeg");
        //设置编码
        response.setCharacterEncoding("utf8");
        //防止浏览器缓存验证码图片
        response.setHeader("Pragma", "No-cache");

    }

    @RequestMapping("/check")
    public boolean check(String captcha, HttpSession session) {
        String code = (String) session.getAttribute(key);


        if (!StringUtils.hasLength(captcha)) {
            return false;
        }

        //从session中获取时间
        Date date = (Date) session.getAttribute(datetime);

        if (date == null || System.currentTimeMillis() - date.getTime() > 60 * 1000) {
            //session为null,或者session过期(超过一分钟就算过期)
            //System.currentTimeMillis() - date.getTime(): 当前时间-请求时间
            return false;
        }

        //不区分大小写
        return captcha.equalsIgnoreCase(code);
    }
}
